package heven.holt.library.extensions

import android.view.View
import android.view.ViewTreeObserver
import android.view.Window
import heven.holt.library.listener.OnSoftInputChangedListener


private val TAG_ON_GLOBAL_LAYOUT_LISTENER = "softInputChangedListener".hashCode()

fun View.registerSoftInputChangedListener(listener: OnSoftInputChangedListener) {
    val window: Window = context.getActivity()?.window ?: return
    var decorViewInvisibleHeight = window.getDecorViewInvisibleHeight()
    val onGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
        val height = window.getDecorViewInvisibleHeight()
        if (decorViewInvisibleHeight != height) {
            listener.onSoftInputChanged(height)
            decorViewInvisibleHeight = height
        }
    }
    viewTreeObserver.addOnGlobalLayoutListener(onGlobalLayoutListener)
    setTag(TAG_ON_GLOBAL_LAYOUT_LISTENER, onGlobalLayoutListener)
}

fun View.unregisterSoftInputChangedListener() {
    val tag = getTag(TAG_ON_GLOBAL_LAYOUT_LISTENER)
    if (tag is ViewTreeObserver.OnGlobalLayoutListener) {
        viewTreeObserver.removeOnGlobalLayoutListener(tag)
    }
}

